//
//  RecemmendTableViewController.m
//  Car
//
//  Created by lanou on 15/9/17.
//  Copyright (c) 2015年 朱鸿儒. All rights reserved.
//

#import "RecemmendTableViewController.h"
#import "SortTableViewCell.h"
#import "RecommendHeaderScrollView.h"
#import "RecommendModel.h"
#import "SearchTableViewController.h"
#import "MyHistory.h"


@interface RecemmendTableViewController ()
{
    
    RecommendHeaderScrollView *myScrollView;
    
}

@property (nonatomic, strong) NSString *myUrl;
@property (nonatomic) BOOL openFirst;
//  存放model的数组
@property (nonatomic, strong) NSMutableArray *modelArray;

@property (nonatomic, strong) NSString *no_row;

//  轮播图
@property (nonatomic, strong) NSMutableArray *scrollArray;
@property (nonatomic, strong) UIPageControl *pageCtrl;


//  下拉刷新控制
@property (nonatomic) NSInteger numberCtrl;

@end

@implementation RecemmendTableViewController






#pragma mark --- 数据解析 --- 

//  轮播图
- (void)reloadWithJson {
    
    [LORequestManger GET:kUrlScroll success:^(id response) {
        
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *ric = dic[@"result"];
        for (NSDictionary *pic in ric[@"focusimg"]) {
            
            [self.scrollArray addObject:pic[@"imgurl"]];
        
        }
        
        [self.tableView reloadData];
        //  设置 header
        [self setUpHeaderViewAndNavigationBar];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}


//  tableView cell
- (void)reloadRecommendWithJson {

    [self changeView];

    if (self.openFirst) {
        self.myUrl = kUrlNews;
    }
    else {
        NSArray *urlArray = @[kUrlNews,kUrlEvaluate,kUrlShoppingGuide,kUrlUsingCar,kUrlTechnology,kUrlCulture,kUrlTravels,kUrlLobbyist,kUrlRemould];

        self.myUrl = urlArray[[self.no_row integerValue]];
        
    }
    
 
    [LORequestManger GET:self.myUrl success:^(id response) {
        if ([self.myUrl isEqualToString:kUrlLobbyist]) {
            NSDictionary *dic = (NSDictionary *)response;
            NSDictionary *ric = dic[@"result"];
            for (NSDictionary *nic in ric[@"list"]) {
                
                RecommendModel *model = [RecommendModel shareJsonWithDictionary:nic];
                
                [self.modelArray addObject:model];
                
            }
            
            //  翻页效果
//            [self changeView];
            
            [self.tableView reloadData];

        }
        else {
            NSDictionary *dic = (NSDictionary *)response;
            NSDictionary *ric = dic[@"result"];
            for (NSDictionary *nic in ric[@"newslist"]) {
                
                RecommendModel *model = [RecommendModel shareJsonWithDictionary:nic];
                
                [self.modelArray addObject:model];
                
            }
            if (self.openFirst == YES) {
                [self.tableView reloadData];
            }
            else {
//                [self changeView];
                
                [self.tableView reloadData];

            }
            


        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    

//    [self changeView];
    
}


#pragma mark ---   数据解析之前执行 页面的动画效果

- (void)changeView {
    
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:2.0f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES];
    
    [UIView commitAnimations];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.openFirst = YES;
    
    [self pushToRefreashAndLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(show:) name:@"tm" object:nil];
    


    [self reloadRecommendWithJson];
    if ([Setting shareWithSetting].isOnPic == NO) {
    [self reloadWithJson];
    }
    

    //  注册
    [self.tableView registerClass:[SortTableViewCell class] forCellReuseIdentifier:@"tm"];
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(circulary) userInfo:nil repeats:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark ---  上拉加载 下拉刷新

- (void)pushToRefreashAndLoad {
    
    
    __block RecemmendTableViewController *TVC = self;
    [self.tableView addHeaderWithCallback:^{
        
        TVC.openFirst = NO;
        
        [TVC reloadRecommendWithJson];
        
        [TVC.tableView headerEndRefreshing];
    }];
    
//    [self.tableView addFooterWithCallback:^{
//        
//        TVC.numberCtrl = 2;
//        
//        
//        
//        [LORequestManger GET:TVC.myUrl success:^(id response) {
//            
//            if ([TVC.myUrl isEqualToString:kUrlLobbyist]) {
//                
//                NSDictionary *dic = (NSDictionary *)response;
//                NSDictionary *ric = dic[@"result"];
//                for (NSDictionary *nic in ric[@"list"]) {
//                    
//                    RecommendModel *model = [RecommendModel shareJsonWithDictionary:nic];
//                    
//                    [TVC.modelArray addObject:model];
//                    
//                }
//                
//                [TVC.tableView reloadData];
//                
//            }
//            else {
//                NSDictionary *dic = (NSDictionary *)response;
//                NSDictionary *ric = dic[@"result"];
//                for (NSDictionary *nic in ric[@"newslist"]) {
//                    
//                    RecommendModel *model = [RecommendModel shareJsonWithDictionary:nic];
//                    
//                    [TVC.modelArray addObject:model];
//                    
//                }
//                if (TVC.openFirst == YES) {
//                    [TVC.tableView reloadData];
//                }
//                else {
//                    
//                    [TVC.tableView reloadData];
//                    
//                }
    
                
                
//            }
//            
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            
//        }];
//
//        
//        
//    }];
    
    
}





#pragma mark --- 设置导航条和header轮播图 ---

- (void)setUpHeaderViewAndNavigationBar {
    
    //  导航条设置不透明
    self.navigationController.navigationBar.translucent = NO;
    
    //  设置导航条上的按钮
    UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(actionClickSearch)];
    self.navigationItem.rightBarButtonItem = searchButton;
    //  设置导航条的标题
    self.navigationItem.title = @"车行家";
    
    _pageCtrl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 230, kWidth, 20)];
    _pageCtrl.currentPage = 0;
    _pageCtrl.numberOfPages = self.scrollArray.count;
    [_pageCtrl addTarget:self action:@selector(pageTrun:) forControlEvents:UIControlEventValueChanged];
    _pageCtrl.tag = 1000;
    

     myScrollView = [[RecommendHeaderScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 250) imageArray:self.scrollArray delegate:self timer:1 action:nil];
    myScrollView.backgroundColor = [UIColor whiteColor];
     myScrollView = [[RecommendHeaderScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kWidth /2) imageArray:self.scrollArray delegate:self timer:1 action:nil];
    myScrollView.tag = 2000;
    //  指示条状态
    myScrollView.showsHorizontalScrollIndicator = NO;
    
    self.tableView.tableHeaderView = myScrollView;
    [self.view addSubview:_pageCtrl];

}







- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.tag == 2000) {
        
        UIPageControl *pageC = (UIPageControl *)[self.view viewWithTag:1000];
        pageC.currentPage = scrollView.contentOffset.x / kWidth;

    }
    
    
}





- (void)pageTrun:(UIPageControl *)pageControl {
    
    
}




- (void)actionClickSearch {
    
    NSLog(@"搜索！！！！！");
    
    SearchTableViewController *search = [[SearchTableViewController alloc] init];
    
    
    [self.navigationController pushViewController:search animated:YES];
    
}



#pragma mark - Table view data source


//  区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    
    return 1;
}


//  行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    
    return self.modelArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;
    
}




//  cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SortTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tm" forIndexPath:indexPath];
    
    RecommendModel *model = self.modelArray[indexPath.row];
    
    [cell setValueWithModel:model];

    
    return cell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CATransform3D rotation;//3D旋转
    rotation = CATransform3DMakeRotation( (10.0*M_PI)/180, 0.0, 0.7, 0.4);
    //逆时针旋转
    rotation.m34 = 1.0 / - 1000;
    
//        cell.layer.shadowColor = [[UIColor blackColor]CGColor];
//        cell.contentView.layer.shadowOffset = CGSizeMake(0, 0);
//        cell.alpha = 0.6;
    
    cell.contentView.layer.transform = rotation;    //旋转定点
    cell.contentView.layer.anchorPoint = CGPointMake(0, 3);
    
    [UIView animateWithDuration:0.8 animations:^{
        cell.contentView.layer.transform = CATransform3DIdentity;
        cell.alpha = 1;
        //        cell.contentView.layer.shadowOffset = CGSizeMake(0, 0);
    }];
    
}






#pragma mark ---   跳转到二级页面

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    WebViewController *webVC = [[WebViewController alloc] init];
    
    RecommendModel *model = self.modelArray[indexPath.row];
    
    webVC.changedID = model.ID;
//添加到历史记录
	[[MyHistory shareHistory] addHistoryModel:model WithUser:[EnterInformationHandle share].myNumber];
    [self.navigationController pushViewController:webVC animated:YES];
}



#pragma mark --- 懒加载 ---

- (NSMutableArray *)modelArray {
    if (!_modelArray) {
        _modelArray = [NSMutableArray array];
    }
    
    return _modelArray;
    
}


- (NSMutableArray *)scrollArray {
    if (!_scrollArray) {
        _scrollArray = [NSMutableArray array];
    }
    
    return _scrollArray;
}


- (void)show:(NSNotification *)no {
    
    [self.modelArray removeAllObjects];
    self.no_row = no.userInfo[@"key"];
    
    self.openFirst = NO;
    
    [self reloadRecommendWithJson];
}

-(void)circulary{
    //创建一个newPoint每次被赋予当前scrollView的contentOfset
    CGPoint newPoint = myScrollView.contentOffset;
    newPoint.x += kWidth;
    if (newPoint.x == 6 * kWidth) {
        newPoint.x = 0;
    }
    int a = newPoint.x / kWidth;
    self.pageCtrl.currentPage = a;
    
    [myScrollView setContentOffset:newPoint animated:YES];
    
}


@end
